package com.citydo.webrtcspringboot.transfer.udp;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.citydo.webrtcspringboot.GlobalConfig;
import com.citydo.webrtcspringboot.MessageType;
import com.citydo.webrtcspringboot.component.ThreadPool;
import com.citydo.webrtcspringboot.transfer.mqtt.TBMqttClient;
import com.citydo.webrtcspringboot.websocket.stream.WebsocketService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.List;


//接收UDP消息的服务
@Slf4j
@Component
public class UdpServer {
    @Value("11301")
//    @Value("9090")
    private String port;
    private DatagramSocket socket;
    byte[] buffer = new byte[1024];
    DatagramPacket packet;
    public static int CurrentMode = Mode.hotExtremely;

    @PostConstruct
    public void start() throws SocketException {
        socket = new DatagramSocket(Integer.parseInt(port));
        packet = new DatagramPacket(buffer, buffer.length);
        new Thread(() -> {
            while (true) {
                try {
                    socket.receive(packet);
                    String message = new String(packet.getData(), 0, packet.getLength());
//                    UdpVoltage voltage = JSON.parseObject(message,UdpVoltage.class);
//                    log.info("接收的消息:" + voltage.AD.get(0));
                    JSONObject obj = JSON.parseObject(message);
//                    String mode = null;
                    JSONObject sendMsg = new JSONObject();
                    sendMsg.put("mode", CurrentMode);
                    sendMsg.put("AD",message);
//                    sendMsg.put("rotation", ((List<Float>) obj.get("AD")).get(0));
                    if (obj.get("AD") != null) {
                        //如果消息类型为MQTT消息，则发送MQTT
                        if(GlobalConfig.MESSAGE_TYPE == MessageType.MQTT) {
                            if (TBMqttClient.IMqttAsyncClient.isConnected()) {
                                TBMqttClient.IMqttAsyncClient.publish(TBMqttClient.SteamRotationTopic,
                                        new MqttMessage(sendMsg.toJSONString().getBytes()));
                            }
                        }
                        //如果消息类型为WEBSOCKET则发送WEBSOCKET
                        else if (GlobalConfig.MESSAGE_TYPE == MessageType.WEBSOCKET) {
                            WebsocketService.Instance.SendMsg(sendMsg.toJSONString());
                        }
//                        WebsocketService.Instance.SendMsg(sendMsg.toJSONString());
                    } else if (obj.get("mode") != null) {
                        CurrentMode = (int) obj.get("mode");
                    }
//                    log.info("接收的消息:" + message);
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

//        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        // 创建一个定时任务
        Runnable task = () -> {
            try {
                socket.receive(packet);
                String message = new String(packet.getData(), 0, packet.getLength());
                log.info("接收的消息:" + message);
                JSONObject obj = JSON.parseObject(message);
                JSONObject sendMsg = new JSONObject();
                String mode = null;
                switch (CurrentMode) {
                    case Mode.hotExtremely:
                        mode = "极热态";
                        break;
                    case Mode.cold:
                        mode = "冷态";
                        break;
                    case Mode.hot:
                        mode = "热态";
                        break;
                    case Mode.warm:
                        mode = "温态";
                        break;
                }
                sendMsg.put("mode", mode);
                sendMsg.put("rotation", ((List<Float>) obj.get("AD")).get(0));
                if (obj.get("AD") != null) {
                    WebsocketService.Instance.SendMsg(message);
                } else if (obj.get("mode") != null) {
                    CurrentMode = (int) obj.get("mode");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        };

        // 定时任务延迟1秒后开始执行，然后每隔100毫秒秒执行一次
//        ThreadPool.Instance.scheduler.scheduleAtFixedRate(task, 1, 500, TimeUnit.MILLISECONDS);
//        System.out.println("Received message: " + message);
    }
}


